!function () {
    var urlEl, qrcodeEl, lastURL;

    var ready = function () {
        elInit();
        evInit();

        lastURL = '';
        urlEl.focus();
    };

    var elInit = function () {
        urlEl = document.getElementById('url');
        qrcodeEl = document.getElementById('qrcode');
    };

    var evInit = function () {
        if (urlEl) {
            urlEl.addEventListener('change', evChangeQR);
            urlEl.addEventListener('keyup', evChangeQR);
            urlEl.addEventListener('click', evTextSelectAll);
        }
    };

    var evTextSelectAll = function (ev) {
        this.setSelectRange = this.value.length;
        this.select();
    };

    var evChangeQR = function (ev) {
        var qrcode;

        if (urlEl.value == lastURL)
            return;
        
        qrcodeEl.innerHTML = '';

        if (urlEl.value == '')
            return;

        qrcode = new QRCode(
            qrcodeEl,
            {
                width: 200, height: 200,
                colorDark: '#000', colorWhite: '#fff',
                correctLevel: QRCode.CorrectLevel.H
            }
        );
        qrcode.clear();

        setTimeout(function () {
            qrcode.makeCode(urlEl.value);
            qrcode = null;
            urlEl.setAttribute('title', urlEl.value);
        }, 200);

        lastURL = urlEl.value;
        urlEl.setSelectionRange(0, 0);
    };

    window.addEventListener('load', ready);
} ();